<template>
  <div class="page-container">
    <a-card :bordered="false" size="small" style="margin-bottom: 10px">
      <a-row :gutter="16">
        <a-col class="search-row" :span="20">
          <a-form layout="inline">
            <a-form-item label="所在周期">
              <a-date-picker
                size="small"
                v-model:value="queryParams.period"
                :picker="picker"
                :allow-clear="false"
                :disabled-date="disabledDate"
                @change="getOpenStatus"
              />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" size="small" @click="getOpenStatus">查询</a-button>
            </a-form-item>
          </a-form>
          <div class="status-item">
            <span class="label">发布状态：</span>
            <span class="value">
              <a-tag :color="openStatus === '开启填报' ? 'green' : 'red'">{{ openStatus }}</a-tag>
            </span>
          </div>
          <div class="status-item">
            <span class="label">整体填报状态：</span>
            <span class="value">{{ isAllFill ? '已填报' : '填报中' }}</span>
          </div>
        </a-col>
        <a-col class="search-row right-btn-container" :span="4">
          <a-button
            type="primary"
            danger
            size="small"
            @click="handleResetAll"
            :disabled="openStatus !== '开启填报' && !dataSource.length"
            >全部重新填报</a-button
          >
        </a-col>
      </a-row>
    </a-card>

    <a-table
      :dataSource="dataSource"
      :columns="columns"
      :pagination="{ pageSize: 15 }"
      size="small"
    >
      <template #bodyCell="{ record, column }">
        <template v-if="column.dataIndex === 'sheetName'">
          <a v-if="openStatus === '开启填报'" href="javascript:;" @click="handleOpenUrl(record)">{{
            record.sheetName
          }}</a>
          <span v-else style="color: #666">{{ record.sheetName }}</span>
        </template>
        <template v-if="column.dataIndex === 'operation'">
          <a style="margin-right: 10px" @click="handleDownload(record)">下载表格</a>
          <a
            v-if="openStatus === '开启填报'"
            style="margin-right: 10px"
            @click="handleReset(record)"
            >重新填报</a
          >
          <span v-if="openStatus !== '开启填报'" style="margin-right: 10px; color: #666 !important"
            >重新填报</span
          >
          <a
            style="margin-right: 10px"
            @click="handleComplete(record)"
            v-if="record.fillState !== '已填报' && openStatus === '开启填报'"
            >填报完成</a
          >
          <span
            style="margin-right: 10px"
            v-if="record.fillState !== '已填报' && openStatus !== '开启填报'"
            >填报完成</span
          >
        </template>
      </template>
    </a-table>
  </div>
</template>

<script setup>
import { nextTick, onMounted, reactive, ref, watch } from 'vue'
import { projectTemplateColumns as columns } from '@/config/columns'
import { message, Modal } from 'ant-design-vue'
import dayjs from 'dayjs'
import { useRoute } from 'vue-router'
import {
  createCopySheetsForDepartmentApi,
  downloadSheetApi,
  finishFillSheetApi,
  getProjectFileDataListOfDepartmentApi,
  getProjectOpenStatusApi,
  reFillAllSheetApi,
  reFillSheetApi
} from '@/api/busi'
import useUserStore from '@/stores/user'
import { appId, outUrl } from '@/config'
import { createUuid } from '@/utils/encryp'

const route = useRoute()
const userStore = useUserStore()
// const formRef = ref()
// const form = reactive({})
// const visible = ref(false)
// const title = ref('新增')
const dataSource = ref([])
const total = ref(0)
const queryParams = reactive({
  period: dayjs()
})
const picker = ref('month') // 统计年度/月度 month/year
const projectDetail = ref({})
const openStatus = ref('')
const isAllFill = ref(false)

watch(
  () => route.params,
  () => {
    init()
  }
)

const handleOpenUrl = (row) => {
  let str = `${row.sheetID}+${userStore.token}+${createUuid()}`
  const iframe = document.getElementById('encryptIFrame')
  try {
    iframe.contentWindow.OTPEncrypt(appId, str, (res) => {
      let url = `${window.outUrl}?sid=${res}`
      window.open(url)
    })
  } catch (err) {
    console.log(err)
  }
}

const disabledDate = (current) => {
  // Can not select days before today and today
  if (picker.value === 'year') {
    return current && current.isAfter(dayjs(dayjs().add(1, 'year').format('YYYY-01-01')))
  } else {
    return current && current.isAfter(dayjs(dayjs().add(1, 'month').format('YYYY-MM-01')))
  }
}
const getList = async () => {
  let { id, periodType } = projectDetail.value
  let params = {
    ProjectId: id,
    PeriodId:
      periodType === '年度'
        ? dayjs(queryParams.period).format('YYYY')
        : dayjs(queryParams.period).format('YYYYMM'),
    DepartmentId: userStore.userInfo.departmentId
  }
  if (openStatus.value === '开启填报') {
    await createCopySheetsForDepartmentApi(params)
  }
  let res = await getProjectFileDataListOfDepartmentApi(params)
  if (res) {
    dataSource.value = res.items.map((item) => {
      item.lastModifyTime = dayjs(item.lastModifyTime).format('YYYY-MM-DD HH:mm:ss')
      return item
    })
    isAllFill.value = res.items.length && res.items.every((item) => item.fillState === '已填报')
  }
}

const getOpenStatus = () => {
  isAllFill.value = false
  dataSource.value = []

  if (projectDetail.value.id) {
    let params = {
      ProjectId: route.params.id
    }
    if (projectDetail.value.periodType === '年度') {
      params.PeriodId = dayjs(queryParams.period).format('YYYY')
    } else {
      params.PeriodId = dayjs(queryParams.period).format('YYYYMM')
    }

    getProjectOpenStatusApi(params).then((res) => {
      openStatus.value = res && res.openStatus ? res.openStatus : '关闭发布'
      // if (res && res.openStatus && res && res.openStatus === '开启填报') {
      handleSearch()
      // } else {

      // }
    })
  }
}

const handleSearch = () => {
  queryParams.page = 1
  getList()
}
const handleDownload = async (row) => {
  if (openStatus.value !== '开启填报') return

  let res = await downloadSheetApi({ fid: row.id })
  // 创建一个标签
  let link = document.createElement('a')
  //
  // let blob = new Blob([res], {
  //   type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'
  // })

  // link.href = window.URL.createObjectURL(blob)
  link.href = res
  // 设置文件下载的名称，（自定义）
  link.download = `${
    projectDetail.value.periodType === '年度'
      ? dayjs(queryParams.period).format('YYYY')
      : dayjs(queryParams.period).format('YYYYMM')
  }-${row.sheetName}`
  // 模拟点击事件，此时页面将进行下载
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// const handleOk = () => {
//   formRef.value
//     .validateFields()
//     .then(() => {
//       if (title.value === '新增') {
//         //
//       } else {
//         //
//       }
//       visible.value = false
//     })
//     .catch(() => {})
// }

const handleComplete = (row) => {
  if (openStatus.value !== '开启填报') return
  finishFillSheetApi({
    SheetId: row.id,
    DepartmentId: userStore.userInfo.departmentId
  }).then(() => {
    message.success('操作成功')
    getList()
  })
}

const handleReset = (row) => {
  if (openStatus.value !== '开启填报') return
  Modal.confirm({
    title: '提示',
    content: '重新填报将清除原有数据,请确认是否要继续?',
    onOk: () => {
      reFillSheetApi({
        SheetId: row.sheetID,
        DepartmentId: userStore.userInfo.departmentId
      }).then(() => {
        nextTick(() => {
          // message.success('操作成功')
        })
        getList()
      })
    }
  })
}
const handleResetAll = () => {
  if (openStatus.value !== '开启填报') return
  Modal.confirm({
    title: '提示',
    content: '全部重新填报将清除所有模板的原有数据,请确认是否要继续?',
    onOk: () => {
      let { id, periodType } = projectDetail.value
      let params = {
        ProjectId: id,
        PeriodId:
          periodType === '年度'
            ? dayjs(queryParams.period).format('YYYY')
            : dayjs(queryParams.period).format('YYYYMM'),
        DepartmentId: userStore.userInfo.departmentId
      }
      reFillAllSheetApi(params).then(() => {
        message.success('操作成功')
        getList()
      })
    }
  })
}

const init = () => {
  dataSource.value = []
  total.value = 0
  queryParams.period = dayjs()
  picker.value = 'month' // 统计年度/月度 month/year
  projectDetail.value = {}
  openStatus.value = ''
  isAllFill.value = false

  projectDetail.value = userStore.menuList.find((item) => item.id === route.params.id)
  if (projectDetail.value) {
    if (projectDetail.value.periodType === '年度') {
      picker.value = 'year'
    } else {
      picker.value = 'month'
    }
    getOpenStatus()
  }
}

onMounted(() => {
  init()
})
</script>

<style lang="less" scoped>
.search-row {
  .status-item {
    margin-right: 30px;
    height: 20px;
    line-height: 20px;
    .label {
    }
    .value {
      font-weight: bold;
      color: #999;
    }
  }
}
</style>
